package com.mspbots.script.api;

import cn.hutool.core.lang.Assert;
import com.mspbots.script.model.TriggerEventDTO;
import com.mspbots.script.service.ScriptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.util.concurrent.Callable;

@Slf4j
@RestController
@RequestMapping("execute")
public class ScriptController {

    @Autowired
    private ScriptService service;
    @Autowired
    private RabbitMessagingTemplate messagingTemplate;

    @GetMapping("system-script/{id}")
    public Callable systemScript(@PathVariable Long id) {
        return () -> service.executeSystemScript(id);
    }

    @GetMapping("tenant-script/{id}")
    public Callable tenantScript(@PathVariable Long id) {
        return () -> service.executeTenantScript(id);
    }

    @PostMapping("event")
    public Callable executeEvent(@RequestBody TriggerEventDTO triggerEventDTO) {
        return () -> {
            Assert.notNull(triggerEventDTO.getScope());
            Assert.notNull(triggerEventDTO.getEventName());
            return service.execute(triggerEventDTO);
        };
    }

    //
    @PostMapping("mq-event")
    public Callable execute(@RequestBody TriggerEventDTO triggerEventDTO) {
        return () -> {
            Assert.notNull(triggerEventDTO.getScope());
            Assert.notNull(triggerEventDTO.getEventName());
            this.messagingTemplate.convertAndSend("msp.trigger.event", "", triggerEventDTO);
            log.debug("cw msp.trigger.event [{}] [{}] ", triggerEventDTO.getScope(), triggerEventDTO.getPayload());
            return true;
        };
    }


    @PostMapping("event/ticket")
    public Mono<Object> executeTicket(@RequestBody TriggerEventDTO triggerEventDTO) {
        Assert.notNull(triggerEventDTO.getId());
        return service.executeById(triggerEventDTO);
    }
}
